package pers.qianyu.month_202012.date_20201201;

import java.util.*;

/**
 * [与 date_2020111 相同（状态压缩版）]
 * 53. 最大子序和
 * https://leetcode-cn.com/problems/maximum-subarray/
 *
 * @author mizzle rain
 * @date 2020-12-01 15:30
 */
public class MaxSubArray {
    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new RuntimeException("invalid parameter");
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        for (int i = 1; i < dp.length; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
        }
        int res = dp[0];
        System.out.println(Arrays.toString(dp));
        for (int i = 1; i < dp.length; i++) {
            if (res < dp[i]) {
                res = dp[i];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        int result = new MaxSubArray().maxSubArray(arr);
        System.out.println("result = " + result);
    }
}
